package com.janj.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//自定义的工具类

public class JDBCUtils {
    static String url;
    static String username;
    static String password;
    static String dirverName;

    static {
        url = "jdbc:mysql://192.168.65.47:3306/duod9";
        username = "root";
        password = "root";
        dirverName = "com.mysql.jdbc.Driver";
    }


    static {
        try {
            //1.获取到类加载器

            ClassLoader loader = ClassLoader.getSystemClassLoader();

            //2.获取流对象
            InputStream is = loader.getResourceAsStream("jdbc.properties");

            //3.创建Properties对象,加载数据
            Properties pp = new Properties();
            pp.load(is);

            //4.通过键获取值
            url = pp.getProperty("url");
            username =pp.getProperty("username");
            password =pp.getProperty("password");
            dirverName =pp.getProperty("dirverName");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static Connection getConnection() {
        Connection conn = null;
        try {

            Class.forName(dirverName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

     public static void close(Connection conn, Statement stat){
          close(conn, stat ,null);
     }

     public static void close(Connection conn, Statement stat, ResultSet resu){
         if (resu != null) {
             try {
                 resu.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

         if (stat != null) {
             try {
                 stat.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

         if (conn != null) {
             try {
                 conn.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
    }


}
